package com.xiaoyu.lanling.router.deeplink;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.xiaoyu.lanling.common.Constant;

import java.util.Set;

class DeepLinkEntry {

    final Uri uri;
    final Class<? extends Activity> activityClass;
    final boolean needLogin;
    private final IntentParamsParser intentParamsParser;

    static DeepLinkEntry createForApp(Uri uri, Class<? extends Activity> activityClass, boolean needLogin) {
        return new DeepLinkEntry(uri, activityClass, needLogin, new AppIntentParamsParser());
    }

    static DeepLinkEntry createForWeex(Uri uri, Class<? extends Activity> activityClass, boolean needLogin) {
//        return new DeepLinkEntry(uri, activityClass, needLogin, new WeexIntentParamsParser());
        return null;
    }

    static DeepLinkEntry createForWeb(Uri uri, Class<? extends Activity> activityClass, boolean needLogin) {
        return new DeepLinkEntry(uri, activityClass, needLogin, new WebIntentParamsParser());
    }

    private DeepLinkEntry(Uri uri, Class<? extends Activity> activityClass, boolean needLogin, IntentParamsParser intentParamsParser) {
        this.uri = uri;
        this.activityClass = activityClass;
        this.needLogin = needLogin;
        this.intentParamsParser = intentParamsParser;
    }

    Intent buildIntent(Context context) {
        Bundle params = intentParamsParser.parse(uri);
        Intent intent = new Intent(context, activityClass);
        intent.setData(uri);
        intent.putExtras(params);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        return intent;
    }

    @Override
    public String toString() {
        return "DeepLinkEntry{" +
                "uri=" + uri +
                ", activityClass=" + activityClass +
                ", needLogin=" + needLogin +
                ", intentParamsParser=" + intentParamsParser +
                '}';
    }

    private interface IntentParamsParser {

        Bundle parse(Uri uri);
    }

    private static class AppIntentParamsParser implements IntentParamsParser {

        @Override
        public Bundle parse(Uri uri) {
            Bundle params = new Bundle();
            Set<String> keys = uri.getQueryParameterNames();
            for (String key : keys) {
                String value = uri.getQueryParameter(key);
                params.putString(key, value);
            }
            return params;
        }
    }


    private static class WebIntentParamsParser implements IntentParamsParser {

        @Override
        public Bundle parse(Uri uri) {
            Bundle params = new Bundle();
            params.putString(Constant.PARAM_URL, uri.toString());
            return params;
        }
    }
}
